/*
	Copyright (C) 2011 Daniel C. Dennison (dandennison84@gmail.com).  All rights reserved.
	This file is licensed under the EPL 1.0 (Eclipse Public License 1.0)
	A copy of the license can be found at http://www.eclipse.org/legal/epl-v10.html
*/

package com.gmail.dandennison84.accounting

import org.junit.Test
import org.junit.Before

class JournalEntryTest {
	JournalEntry je
	Account debitAccount, creditAccount
	JournalEntryAmount debitEntry, creditEntry
	@Before
	void before() {
		je = new JournalEntry(id:1, dateTime:new Date(1), description:'description')
		creditAccount =  new Account(name:'credit', accountType:AccountType.LIABILITIES, balanceType:BalanceType.CREDIT, closingType:ClosingType.PERMANENT,
			cashFlowStatementType:CashFlowStatementType.OPERATING_ACTIVITIES)
		debitAccount = new Account(name:'debit', accountType:AccountType.ASSETS, balanceType:BalanceType.DEBIT, closingType:ClosingType.PERMANENT,
			cashFlowStatementType:CashFlowStatementType.OPERATING_ACTIVITIES)
		creditEntry = new JournalEntryAmount(account:creditAccount, amount:5.0)
		debitEntry = new JournalEntryAmount(account:debitAccount, amount:4.0)
	}

	@Test
	void setId() {
		assert 1 == je.id
	}


	@Test
	void setDateTime() {
		Date date = new Date(1)
		assert date == je.dateTime
	}

	@Test
	void setPosted() {
		assert !je.posted
		je.posted = true
		assert je.posted
	}

	@Test
	void setDescription() {
		assert 'description' == je.description
	}

	@Test
	void addDebitAccount() {
		je.debits.add(debitEntry)
		assert debitEntry == je.debits[0]
	}

	@Test
	void addCreditAccount() {
		je.credits.add(creditEntry)
		assert creditEntry == je.credits[0]
	}

	@Test
	void testFind() {
		je.credits.add(creditEntry)
		je.debits.add(debitEntry)
		assert debitAccount == je.findDebitAccountByName('debit')?.account
		assert creditAccount == je.findCreditAccountByName('credit')?.account
		assert null == je.findDebitAccountByName('x')
	}

	@Test
	void balance() {
		je.credits.add(creditEntry)
		je.debits.add(debitEntry)
		assert -1.0 == je.balance()
	}

	@Test
	void testPost() {
		Account cashAccount = new Account(name:'cash', accountType:AccountType.LIABILITIES, balanceType:BalanceType.CREDIT, closingType:ClosingType.PERMANENT,
			cashFlowStatementType:CashFlowStatementType.OPERATING_ACTIVITIES)
		Account equipmentAccount = new Account(name:'equipment', accountType:AccountType.LIABILITIES, balanceType:BalanceType.CREDIT, closingType:ClosingType.PERMANENT,
			cashFlowStatementType:CashFlowStatementType.OPERATING_ACTIVITIES)
		JournalEntryAmount debitCash = new JournalEntryAmount(account:cashAccount, amount:5.0)
		JournalEntryAmount creditEquipment = new JournalEntryAmount(account:equipmentAccount, amount:5.0)
		je.debits.add(debitCash)
		je.credits.add(creditEquipment)
		je.post()
		assert je.posted
		assert cashAccount.entries.size() == 1
		assert cashAccount.entries[0] == je
		assert equipmentAccount.entries.size() == 1
		assert equipmentAccount.entries[0] == je
	}
}
